<template>
  <el-form ref="ruleFormRef" style="max-width: 40vw;margin: 30vh auto" :model="ruleForm" :rules="rules"
    label-width="auto">
    <el-form-item prop="username">
      <el-input type="text" v-model="ruleForm.username" placeholder="账号:admin" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="ruleForm.password" show-password placeholder="密码:a123456" />
    </el-form-item>
    <el-form-item prop="captcha">
      <el-input type="text" v-model="ruleForm.captcha_code" placeholder="验证码" style="width: 25vw;" />
      <div class="flex-1">
        <img v-bind:src="captcha" alt="" style="float: right;">
      </div>
    </el-form-item>
    <el-form-item class="flex flex-nowrap">
      <el-checkbox v-model="ruleForm.checked" label="自动登录" size="large" />
      <span class="forgetPassword flex-1 text-right text-[#5F8AC9]">忘记密码</span>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)" style="width: 40vw">
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'

import { type FormInstance, type FormRules } from 'element-plus'
import { getCaptcha, loginApi } from '@/Api/loginApi'
import { useRouter } from 'vue-router'

const router = useRouter()

interface RuleForm {
  username: string
  password: string
  checked: boolean
  captcha_code: string
  captcha_id: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  username: '',
  password: '',
  captcha_code: '',
  checked: false,
  captcha_id: ''
})
const captcha = ref()

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: '请输入账号!', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码!', trigger: 'blur' },
  ],
  captcha_code: [
    { required: true, message: '请输入验证码!', trigger: 'blur' },
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const result = await loginApi(ruleForm)
      if (result.code === 200) {
        console.log(result.data)
        localStorage.setItem('login', JSON.stringify(result.data))
        router.push({ name: 'pool' })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

onMounted(async () => {
  const result = await getCaptcha()
  captcha.value = result.image
  ruleForm.captcha_id = result.id
})
</script>

<style scoped></style>
